﻿using System.Diagnostics.Contracts;
using System.IO;

namespace OpenLS.Spreadsheet.Formats.Biff.Records
{
    internal class CFDatabar : CFBase
    {
        private CFVO cfvoDB1;
        private CFVO cfvoDB2;
        private CFColor color;
        private bool fRightToLeft;
        private bool showOnlyBar; //\\
        private byte iPercentMax;
        private byte iPercentMin;
        private byte reserved1;
        private ushort unused;

        public CFDatabar(DataBar dataBar)
        {
            color = new CFColor(dataBar.Color);
            showOnlyBar = !dataBar.ShowValue;
            cfvoDB1 = new CFVO(dataBar.ValueObject1);
            cfvoDB2 = new CFVO(dataBar.ValueObject2);
            iPercentMin = (byte) dataBar.MinimumLength;
            iPercentMax = (byte) dataBar.MaximumLength;
        }

        public CFDatabar()
        {
        }

        private byte Ab
        {
            get
            {
                byte result = 0;
                if (fRightToLeft) result |= 0x01;
                if (showOnlyBar) result |= 0x02;
                return result;
            }
        }

        public override void Read(BinaryReader reader)
        {
            unused = reader.ReadUInt16();
            reserved1 = reader.ReadByte();
            byte ab = reader.ReadByte();
            fRightToLeft = (ab & 0x01) != 0;
            showOnlyBar = (ab & 0x02) != 0;
            Contract.Assert(Ab == ab);
            iPercentMin = reader.ReadByte();
            iPercentMax = reader.ReadByte();

            color = new CFColor();
            color.Read(reader);
            cfvoDB1 = new CFVO();
            cfvoDB1.Read(reader);
            cfvoDB2 = new CFVO();
            cfvoDB2.Read(reader);
        }

        public override void Write(BinaryWriter writer)
        {
            writer.Write(unused);
            writer.Write(reserved1);
            writer.Write(Ab);
            writer.Write(iPercentMin);
            writer.Write(iPercentMax);

            color.Write(writer);
            cfvoDB1.Write(writer);
            cfvoDB2.Write(writer);
        }

        public DataBar ToDataBar(BiffReaderWorksheetContext context)
        {
            var result = new DataBar();
            result.Color = color.ToColor();
            result.ShowValue = !showOnlyBar;
            result.ValueObject1 = cfvoDB1.ToCondition(context);
            result.ValueObject2 = cfvoDB2.ToCondition(context);
            result.MinimumLength = iPercentMin;
            result.MaximumLength = iPercentMax;

            return result;

        }
    }
}